# -*- encoding: utf-8 -*-
import flask
from flask import request
import json
import requests
import hmac
import base64
import hashlib
from chatbot_graph import ChatBotGraph
import time
import datetime

server = flask.Flask(__name__)


# 消息数字签名计算核对
def check_sign(timestamp):
    app_secret = 'PSCUfpo86sV5wW1RexKIGlyoQ_ngpYdnNyT799pda41DKtC2l9GqsHAiDSZFw_j4'
    app_secret_enc = app_secret.encode('utf-8')
    string_to_sign = '{}\n{}'.format(timestamp, app_secret)
    string_to_sign_enc = string_to_sign.encode('utf-8')
    hmac_code = hmac.new(app_secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
    sign = base64.b64encode(hmac_code).decode('utf-8')
    return sign


# 发送消息
def send_text_msg(userid, message, webhook_url, conversationType):
    if conversationType == '2':
        message_json = {
            "msgtype": "markdown",
            "markdown": {
                "title": "机器人回复",
                "text": message
            },
            "at": {
                "atDingtalkIds": [userid],
                "isAtAll": False
            }
        }
    else:
        message_json = {
            "msgtype": "markdown",
            "markdown": {
                "title": "机器人回复",
                "text": message
            }
        }
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 返回发送状态
    requests.post(url=webhook_url, json=message_json, headers=header)


# # 二次确认消息
def send_isTure_msg(medical_dict, senderid, webhook_url, conversationType):
    # medical_dict  {'扁平足': ['disease', 'symptom']}
    str_1 = '您想问的是否是有关'
    str_2 = ''
    str_3 = ''
    for key, value in medical_dict.items():
        str_2 = str_2 + key + '的信息，'
        if 'disease' in value:
            str_3 = str_3 + key + '是一种疾病,'
            isTrue_msg = str_1 + str_2 + str_3 + '您可以：\n' + '3.  根据疾病问症状，如'+key+'有什么症状\n' \
                                                            '4.  根据疾病问病因，如'+key+'的原因\n' \
                                                            '5.  根据疾病问并发症，如'+key+'有什么并发症\n' \
                                                            '6.  根据疾病问宜吃食物、宜吃食谱，如'+key+'能吃什么\n' \
                                                            '6.  根据疾病问忌吃食物，如' + key + '忌口有哪些\n' \
                                                            '7.  根据疾病问常用药品、推荐药品，如'+key+'能吃什么药\n' \
                                                            '8.  根据疾病问预防方式，如'+key+'的预防方式\n' \
                                                            '9.  根据疾病问治疗方式，如'+key+'怎么治\n' \
                                                            '9.  根据疾病问治疗周期等，如' + key + '要治多久\n' \
                                                            '10. 根据疾病问该疾病的易感染人群，如'+key+'的易感染人群\n' \
                                                            '11. 根据疾病问检查科室，如'+key+'挂哪个科室\n' \
                                                            '12. 根据疾病问检查科目，如'+key+'的检查科目'
        elif 'symptom' in value:
            str_3 = str_3 + key + '是一种症状,'
            isTrue_msg = str_1 + str_2 + str_3 + '您可以：\n' + '1. 根据症状问疾病 如：'+key+'有可能是什么病'
        elif 'drug' in value:
            str_3 = str_3 + key + '是一种药品,'
    send_text_msg(senderid, isTrue_msg, webhook_url, conversationType)


# 处理自动回复消息
def handle_info(handler, req_data):
    # 解析用户发送消息 通讯webhook_url
    text_info = req_data['text']['content'].strip()
    webhook_url = req_data['sessionWebhook']
    # senderid为发送者的id，用来辨别发送人
    senderid = req_data['senderId']
    # conversationType 1：单聊 2：群聊
    conversationType = req_data['conversationType']
    print('单群聊', conversationType)
    uid = senderid+'-'+conversationType
    # if senderid not in users.keys():
    #     users[senderid] = datetime.datetime.now()
    # elif senderid in users.keys() and (datetime.datetime.now() - users[senderid]).seconds > 600:
    #     users[senderid] = datetime.datetime.now()

    if uid in users.keys():
        users[uid][0] = datetime.datetime.now()
    else:
        users[uid] = [datetime.datetime.now()]
    print('用户列表及上一次时间：', users)
    text = handler.chat_main(text_info, users, uid, webhook_url, conversationType)

    if type(text) == dict:
        from answer_return import send_isTure_msg
        send_isTure_msg(text, uid, webhook_url, conversationType)
    else:
        send_text_msg(uid, text, webhook_url, conversationType)
    # print()
    # print('发送人id：', users,'返回内容：  ',text)


@server.route("/", methods=['post'])
def get_data():
    # 第一步验证：是否是post请求
    if request.method == "POST":
        # print(request.headers)
        # 签名验证 获取headers中的Timestamp和Sign
        timestamp = request.headers.get('Timestamp')
        sign = request.headers.get('Sign')
        # 第二步验证：签名是否有效
        if check_sign(timestamp) == sign:
            # 获取、处理数据
            req_data = json.loads(str(request.data, 'utf-8'))
            # print(req_data)
            # 调用数据处理函数
            handle_info(handler, req_data)
            # print('验证通过')
            return 'p_pass'

        print('验证不通过')
        return 'p_no_pass'

    print('有get请求')
    return 'p_get'


if __name__ == '__main__':
    handler = ChatBotGraph()
    users = {}
    server.run(host="0.0.0.0", port=8083)
